// src/stores/roleStore.js

import { defineStore } from 'pinia';
import { RoleApi } from '@/api/role/index.js';
import { ElMessage } from "element-plus";

export const useRoleStore = defineStore('role', {
    state: () => ({
        roleList: [],
        pageInfo: {
            pageSize: 10,
            pageNum: 1,
            total: 0,
            totalPage: 0
        }
    }),
    actions: {
        async getRoleList() {
            const res = await RoleApi.getRoleList({
                page: this.pageInfo.pageNum,
                size: this.pageInfo.pageSize
        });
            this.roleList = res.data.records;
            this.pageInfo.pageSize = res.data.pageSize;
            this.pageInfo.pageNum = res.data.pageNumber;
            this.pageInfo.total = res.data.totalRow;
            this.pageInfo.totalPage = res.data.totalPage;
        },

        // 添加角色
        async addRole(role) {
            const res = await RoleApi.addRole(role);
            if (res.code == 200) {
                ElMessage.success('添加角色成功');
                this.getRoleList();
            } else {
                ElMessage.error('添加角色失败');
            }
        },

        // 更新角色信息
        async updateRole(role) {
            console.log("------------------------")
            console.log("role",role)
            const res = await RoleApi.updateRole(role);

            if (res.code == 200) {
                ElMessage.success('更新角色信息成功');
                this.getRoleList();
            } else {
                ElMessage.error('更新角色信息失败');
            }
        },

        // 删除角色
        async deleteRole(id) {
            const res = await RoleApi.deleteRole(id);
            if (res.code == 200) {
                ElMessage.success('删除角色成功');
                this.getRoleList();
            } else {
                ElMessage.error('删除角色失败');
            }
        },
        // 根据ID获取角色信息
        async getRoleById(id) {
            const res = await RoleApi.getRoleById(id);
            if (res.code == 200) {
                this.currentRole = res.data;
                return res.data;
            } else {
                ElMessage.error('获取角色信息失败');
                return null;
            }
        }
    }
});
